import {
    Controller,
    Get,
    Post,
    Body,
    Param,
    Delete,
    Req,
    ForbiddenException,
    UseInterceptors,
    UploadedFile,
    UploadedFiles,
    BadRequestException,
} from '@nestjs/common';
import { UserService } from './user.service';
import { ApiBearerAuth, ApiOperation, ApiProperty, ApiResponse, ApiTags } from '@nestjs/swagger';
import { CreateUserDto } from './dto/create-user.dto';
import { Request, SkipJwtAuth } from '@common/auth';
import { GetUserInfoResult } from './dto/userInfoResult.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { ObjectId } from 'mongoose';
import { isMongoId } from 'class-validator';
@ApiTags('user')
@ApiBearerAuth()
@Controller()
export class UserController {
    constructor(private readonly userService: UserService) {}

    @Post('/user/create')
    create(@Body() createUserDto: CreateUserDto) {
        return this.userService.create(createUserDto);
    }

    @Get('/user')
    findAll() {
        return this.userService.findAll();
    }

    @Get('/user/info')
    @ApiOperation({ summary: '用户信息' })
    @ApiResponse({
        status: 200,
        // description: 'The found record',
        type: GetUserInfoResult,
    })
    getUserInfo(@Req() req: Request): Promise<GetUserInfoResult> {
        return this.userService.getUserInfo(req.user);
    }
    @Get('/user/info/:id')
    @ApiOperation({ summary: '某个用户信息' })
    @ApiResponse({
        status: 200,
        // description: 'The found record',
        // type: GetUserInfoResult,
    })
    getUserInfoById(@Param('id') id: string & ObjectId, @Req() req: Request) {
        if (!isMongoId(id)) {
            throw new BadRequestException('id错误！');
        }
        return this.userService.findById(id, req.user);
    }
    @Post('/user/update/:id')
    @ApiOperation({ summary: '修改用户信息' })
    update(@Param('id') id: string, @Req() req: Request, @Body() updateUserDto: UpdateUserDto) {
        if (req.user._id !== id) {
            throw new ForbiddenException('权限不足');
        }
        console.log(updateUserDto);
        return this.userService.update(id, updateUserDto);
    }

    @Post('/user/upload/avatar')
    @UseInterceptors(FilesInterceptor('files'))
    uploadAvatar(@UploadedFiles() files: Array<Express.Multer.File>, @Req() req: Request) {
        console.log('user: ', req.user);
        console.log(files);
        return this.userService.uploadAvatar(req.user, files);
    }

    @Delete('/user/:id')
    remove(@Param('id') id: string) {
        return this.userService.remove(+id);
    }
}
